#pragma once

#include <iostream>
#include <string>
#include <memory>

#include <cerrno>
#include <cstdio>
#include <cstring>
#include <cassert>

#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "log.hpp"

class Sock
{
public:
    const static int g_backlog = 20;
public:
    Sock(){}
    Sock(uint16_t port, std::string ip = "")
    {}

    int Socket()
    {
        // 创建socket
        int listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0)
        {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "sock: %d", listensock);
        return listensock;
    }

    void Bind(int sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        // bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = ip.empty() ? INADDR_ANY : inet_addr(ip.c_str());
        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(3);
        }
        logMessage(NORMAL, "bind success ...");
    }

    void Listen(int sock)
    {
        // tcp面向连接的，通信前要先建立连接，设置为监听状态，listen
        if (listen(sock, g_backlog) < 0)
        {
            logMessage(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "listen success ...");
    }

    // const std::string& :输入型参数
    // std::string* :输出型参数
    // std::string& :输入输出型参数
    int Accept(int listensock, std::string* ip, uint16_t* port)
    {
        // 获取连接accept
        struct sockaddr_in src; // 客户端addr
        socklen_t len = sizeof(src);
        int servicesock = accept(listensock, (struct sockaddr *)&src, &len);
        if (servicesock < 0)
        {
            logMessage(ERROR, "accept error, %d:%s", errno, strerror(errno));
            return -1; // 获取失败
        }
        if (port) 
            *port = ntohs(src.sin_port);
        if (ip)
            *ip = inet_ntoa(src.sin_addr);
        return servicesock;
    }

    bool Connect(int sock, const std::string& server_ip, const uint16_t& server_port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(server_port);
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());
        if (connect(sock, (struct sockaddr*)&server, sizeof(server)) == 0) return true;
        else false;
    }

    ~Sock()
    {}
};